/**
 * Created by sa on 2016/9/22.
 * casperjs Taobao.js
 */
var fs = require('fs');
var casper = require('casper').create({
  clientScripts: [
    'script/jquery-1.7.1.min.js'      // These two scripts will be injected in remote
  ],
  pageSettings: {
    loadImages: true,
    loadPlugins: false,
    userAgent: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'
  },
  //logLevel: "debug",//日志等级
  logLevel: "error",//日志等级
  verbose: true,    // 记录日志到控制台
  timeout: 60000,//60秒超时，退出
  onWaitTimeout:function(){
    this.echo('-----output-----timeout-----output end-----','Info');
  }
});

var ip = getIP()

var head = {
  method: 'get',
  headers: {
    "X-Forwarded-For": ip,
    "X-Real-IP" : ip,
    "HTTP_CLIENT_IP" : ip
  },
  encoding: 'utf8'
}

//console.log(head.headers['X-Forwarded-For']);

casper.start();

var src = "";

casper.viewport(1024, 1024);

casper.thenOpen('http://www.kaikouyingyu.cn/taobao2.html',
  head,
  function () {

    this.wait(10000, function () {
      //读取广告承载页
      src = this.evaluate(function () {
        var index = Math.floor(Math.random()*7+1)
        //var aswift_1 = $('iframe').contents().find("a:eq("+ index +")").attr("href");

        var href = $('iframe').contents().find("a[class*='-pic']:eq("+ index +")").attr("href");
        return href;
      });

      if (src) {
        //console.log("获取到href")
        //加载解析
        var id = Math.floor(Math.random()*15+1)
        if(id % 5 == 0){
          fs.write("taobao/taibao.txt",ip + "\n" + src + "\n", 'a+');
          openAdUrl();
        }
      }
    });

  })


function openAdUrl() {
  //console.log("casperObj start")
  casper.open(src, head, function () {
    this.scrollToBottom();
  })
  //保存广告图片
  //saveImg('ad');
}
/****/

//保存追踪图片
casper.then(function () {
  var pathP = 'taobao/taoba_tag_' + new Date().valueOf() + '_' + ip+ '.png'
/*  this.captureSelector(pathP, 'body' , {
    top: 0,
    left: 0,
    width: 500,
    height: 500
  });*/

  this.capture(pathP, {
    top: 0,
    left: 0,
    width: 500,
    height: 500
  });
  console.log("tag save img ok");
});


casper.run(function () {
  //this.echo(this.getCurrentUrl());
  this.exit();
});


function getIP(){
  var ip = Math.floor(Math.random()*255+1)
    + '.'
    + Math.floor(Math.random()*255+1)
    + '.'
    + Math.floor(Math.random()*255+1)
    + '.'
    + Math.floor(Math.random()*255+1);
  return ip;
}
